package postgres

import (
	"context"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "ota/collector/logger"
	"ota/config"
	"ota/errors"
	"ota/model"
	"ota/model/entity"
	"ota/utils"
)

var UpgradePlan = &upgradePlan{&execTx{}}

type upgradePlan struct {
	IExecTx
}

func init() {
	Register(UpgradePlan)
}

func (a *upgradePlan) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.UpgradePlan{}
		if dbOta.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := dbOta.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *upgradePlan) Create(ctx context.Context, m *entity.UpgradePlan) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *upgradePlan) Find(ctx context.Context, in *model.UpgradePlanInfoRequest) (*entity.UpgradePlan, error) {
	e := &entity.UpgradePlan{}

	q := GetDB(ctx).Model(&entity.UpgradePlan{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}
	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *upgradePlan) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.UpgradePlan{}).Where("id = ?", id).Updates(dict).Error
}

// Updates
func (a *upgradePlan) Updates(ctx context.Context, ids []int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.UpgradePlan{}).Where("id IN ?", ids).Updates(dict).Error
}

// Delete
func (a *upgradePlan) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.UpgradePlan{}, id).Error
}

// List query list
func (a *upgradePlan) List(ctx context.Context, in *model.UpgradePlanListRequest, opts ...model.QueryOptions) (int, []*entity.UpgradePlan, error) {

	var (
		opt          = model.GetQueryOption(opts...)
		q            = GetDB(ctx).Model(&entity.UpgradePlan{})
		err          error
		total        int64
		upgradePlans []*entity.UpgradePlan
	)

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if in.StrategyId != nil {

		q = q.Where("strategy_id = ?", in.StrategyId)

	}

	if in.Name != nil {

		q = q.Where("name like ?", utils.SqlLike(in.Name))

	}

	if in.TargetType != nil {

		q = q.Where("target_type = ?", in.TargetType)

	}

	if in.StartTime != nil {

		q = q.Where("start_time = ?", in.StartTime)

	}

	if in.Status != nil {

		q = q.Where("status = ?", in.Status)

	}

	if in.Overseer != nil {

		q = q.Where("overseer like ?", in.Overseer)

	}

	if in.QueryCond != nil {
		var qc = &model.OtaUpgradePlanQueryCond{}
		_ = json.Unmarshal(in.QueryCond, qc)

		if len(qc.Users) > 0 {
			q = q.Where("jsonb_array_elements_text(query_cond->'users')::bigint[] && ARRAY[?];", qc.Users)
		}

		if len(qc.EbikeId) > 0 {
			q = q.Where("jsonb_array_elements_text(query_cond->'ebike_id')::bigint[] && ARRAY[?];", qc.EbikeId)
		}

		if len(qc.EBikeType) > 0 {
			q = q.Where("jsonb_array_elements_text(query_cond->'ebike_type')::bigint[] && ARRAY[?];", qc.EBikeType)
		}
	}

	if in.Tester != nil {

		q = q.Where("tester like ?", utils.SqlLike(in.Tester))

	}

	if in.Inspector != nil {

		q = q.Where("inspector like ?", utils.SqlLike(in.Inspector))

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}

	if opt.OnlyList || b {

		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&upgradePlans).Error; err != nil {
			return 0, nil, err
		}
	}

	return int(total), upgradePlans, nil
}

// ExecTransaction execute database transaction
func (a *upgradePlan) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
